<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>学生</title>
    <!-- 页面一打开判断，是否登录了 (是否有token令牌) -->
    <script>
      if (localStorage.getItem('user-token') === null) {
        //直接跳转到登录页
        location.href = 'login.html'
      }
    </script>
    <link rel="stylesheet" href="./bootstrap/bootstrap.min.css" />
    <link rel="stylesheet" href="./bootstrap/bootstrap-icons.css" />
    <link rel="stylesheet" href="./css/common.css" />
    <link rel="stylesheet" href="./css/student.css" />
  </head>
  <body class="application application-offset">
    <div class="container-fluid container-application">
      <div class="sidenav show" id="sidenav-main">
        <!-- Sidenav header -->
        <div class="sidenav-header d-flex align-items-center">
          <a class="navbar-brand" href="./index.html">
            <span class="logo">·ITCAST·</span>
          </a>
        </div>
        <!-- User mini profile -->
        <div
          class="sidenav-user d-flex flex-column align-items-center justify-content-between text-center"
        >
          <!-- Avatar -->
          <div>
            <a href="#" class="avatar rounded-circle avatar-xl">
              <img
                alt="Image placeholder"
                src="https://yanxuan-item.nosdn.127.net/8b27deb1670c53e67c42ca3e1ed6fd12.jpg"
                class=""
              />
            </a>
            <div class="mt-5">
              <h5 class="mb-0 text-white">黑马前端</h5>
              <span class="d-block text-sm text-white opacity-8 mb-3"
                >数据可视化</span
              >
              <a
                href="javascript:;"
                class="btn btn-sm btn-white btn-icon rounded-pill shadow hover-translate-y-n3"
              >
                <span class="btn-inner--text">学前端来黑马</span>
              </a>
            </div>
          </div>
        </div>
        <!-- Application nav -->
        <div class="nav-application clearfix">
          <a href="./index.html" class="btn btn-square text-sm">
            <span class="btn-inner--icon d-block"
              ><i class="bi bi-house bi-2x"></i
            ></span>
            <span class="btn-inner--icon d-block pt-2">首页</span>
          </a>
          <a href="./student.html" class="btn btn-square text-sm active">
            <span class="btn-inner--icon d-block"
              ><i class="bi bi-people bi-2x"></i
            ></span>
            <span class="btn-inner--icon d-block pt-2">学生</span>
          </a>
          <a href="javascript:;" class="btn btn-square text-sm">
            <span class="btn-inner--icon d-block"
              ><i class="bi bi-columns bi-2x"></i
            ></span>
            <span class="btn-inner--icon d-block pt-2">排版</span>
          </a>
          <a href="javascript:;" class="btn btn-square text-sm">
            <span class="btn-inner--icon d-block"
              ><i class="bi bi-files bi-2x"></i
            ></span>
            <span class="btn-inner--icon d-block pt-2">资料</span>
          </a>
          <a href="javascript:;" class="btn btn-square text-sm">
            <span class="btn-inner--icon d-block"
              ><i class="bi bi-receipt bi-2x"></i
            ></span>
            <span class="btn-inner--icon d-block pt-2">就业</span>
          </a>
          <a href="javascript:;" class="btn btn-square text-sm">
            <span class="btn-inner--icon d-block"
              ><i class="bi bi-gear bi-2x"></i
            ></span>
            <span class="btn-inner--icon d-block pt-2">设置</span>
          </a>
        </div>
        <!-- Misc area -->
        <div class="card bg-gradient-warning">
          <div class="card-body">
            <h5 class="text-white">哈喽, 朋友!</h5>
            <p class="text-white mb-4">
              为什么不现在开始学习前端，创造一些令人惊叹的东西呢？
            </p>
            <a
              href="http://itcast.cn"
              class="btn btn-sm btn-block btn-white rounded-pill"
              target="_blank"
              >Get started</a
            >
          </div>
        </div>
      </div>
      <div class="main-content position-relative">
        <nav
          class="navbar navbar-main navbar-expand-lg navbar-dark navbar-border"
          id="navbar-main"
        >
          <div class="container-fluid">
            <!-- Navbar nav -->
            <div
              class="collapse navbar-collapse navbar-collapse-fade"
              id="navbar-main-collapse"
            >
              <ul class="navbar-nav align-items-lg-center">
                <!-- Home  -->
                <li class="nav-item">
                  <a class="nav-link pl-lg-0" href="./index.html"> 首页 </a>
                </li>
                <li class="nav-item">
                  <a class="nav-link pl-lg-0" href="./index.html"> 传智教育 </a>
                </li>
                <li class="nav-item">
                  <a class="nav-link pl-lg-0" href="./index.html">
                    黑马程序员
                  </a>
                </li>
                <li class="nav-item">
                  <a class="nav-link pl-lg-0" href="./index.html"> 文档 </a>
                </li>
              </ul>
              <!-- Right menu -->
              <ul
                class="navbar-nav ml-lg-auto align-items-center d-none d-lg-flex"
              >
                <li class="nav-item dropdown dropdown-animate">
                  <a
                    class="nav-link pr-lg-0"
                    href=".dropdown-menu"
                    role="button"
                    data-toggle="dropdown"
                    aria-haspopup="true"
                    aria-expanded="false"
                  >
                    <div class="media media-pill align-items-center">
                      <span class="avatar rounded-circle">
                        <img
                          alt="Image placeholder"
                          src="https://yanxuan-item.nosdn.127.net/8b27deb1670c53e67c42ca3e1ed6fd12.jpg"
                        />
                      </span>
                      <div class="ml-2 d-none d-lg-block">
                        <span class="mb-0 text-sm font-weight-bold">Admin</span>
                      </div>
                    </div>
                  </a>
                </li>
                <li class="nav-item">
                  <a class="nav-link pl-lg-0" id="logout" href="javascript:;">
                    退出
                  </a>
                </li>
              </ul>
            </div>
          </div>
        </nav>
        <div class="page-content">
          <div class="page-title mb-3">
            <div class="row justify-content-between align-items-center">
              <div class="col-md-6 mb-3 mb-md-0">
                <h5 class="h3 font-weight-400 mb-0 text-white">Students</h5>
                <span class="text-sm text-white opacity-8"
                  >一共有 <b class="total">0</b> 位学员</span
                >
              </div>
              <div
                class="col-md-6 d-flex align-items-center justify-content-between justify-content-md-end"
              >
                <a
                  id="openModal"
                  href="javascript:;"
                  class="btn btn-sm btn-white btn-icon-only rounded-circle ml-4"
                >
                  <span class="btn-inner--icon"
                    ><i class="bi bi-plus bi-2x"></i
                  ></span>
                </a>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col">
              <div class="card card-fluid">
                <div class="table-responsive" style="min-height: 1000px">
                  <table class="table align-items-center">
                    <thead>
                      <tr>
                        <th>姓名</th>
                        <th>年龄</th>
                        <th>性别</th>
                        <th>组号</th>
                        <th>期望薪资</th>
                        <th>就业薪资</th>
                        <th>籍贯</th>
                        <th>操作</th>
                      </tr>
                    </thead>
                    <tbody class="list">
                      <!-- <tr>
                      <td>张杰</td>
                      <td>20</td>
                      <td>男</td>
                      <td>第2组</td>
                      <td>10000</td>
                      <td>13000</td>
                      <td>北京北京市东城区</td>
                      <td>
                        <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen"></i></a>
                        <a href="javascript:;" class="text-danger"><i class="bi bi-trash"></i></a>
                      </td>
                    </tr> -->
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
          <!-- footer -->
          <div class="footer pt-5 pb-4 footer-light" id="footer-main">
            <div class="row text-center text-sm-left align-items-sm-center">
              <div class="col-sm-6">
                <p class="text-sm mb-0">
                  © 2022
                  <a href="https://itcast.cn" class="h6 text-sm" target="_blank"
                    >前端学科</a
                  >. All rights reserved.
                </p>
              </div>
              <div class="col-sm-6 mb-md-0">
                <ul class="nav justify-content-center justify-content-md-end">
                  <li class="nav-item">
                    <a class="nav-link" href="#">Support</a>
                  </li>
                  <li class="nav-item">
                    <a class="nav-link" href="#">Terms</a>
                  </li>
                  <li class="nav-item">
                    <a class="nav-link pr-0" href="#">Privacy</a>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- add Modal -->
    <div class="modal fade" id="modal">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">添加/编辑学员</h5>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
              aria-label="Close"
            ></button>
          </div>
          <div class="modal-body">
            <form id="form" class="g-3 row" autocomplete="off" novalidate>
              <div class="col-sm-6">
                <div class="form-group">
                  <label class="input-group-label">姓名：</label>
                  <input
                    type="text"
                    name="name"
                    class="form-control"
                    placeholder="请输入姓名"
                  />
                </div>
              </div>
              <div class="col-sm-6">
                <div class="form-group">
                  <label class="input-group-label">性别：</label>
                  <div class="input">
                    <div class="form-check d-inline-block">
                      <input
                        value="0"
                        checked
                        id="cb01"
                        class="form-check-input"
                        type="radio"
                        name="gender"
                      />
                      <label for="cb01" class="form-check-label">男</label>
                    </div>
                    <div class="form-check d-inline-block">
                      <input
                        value="1"
                        id="cb02"
                        class="form-check-input"
                        type="radio"
                        name="gender"
                      />
                      <label for="cb02" class="form-check-label">女</label>
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-sm-6">
                <div class="form-group">
                  <label class="input-group-label">年龄：</label>
                  <input
                    type="text"
                    name="age"
                    class="form-control"
                    placeholder="请输入年龄"
                  />
                </div>
              </div>
              <div class="col-sm-6">
                <div class="form-group">
                  <label class="input-group-label">组号：</label>
                  <input
                    type="text"
                    name="group"
                    class="form-control"
                    placeholder="请输入1-8组号"
                  />
                </div>
              </div>
              <div class="col-sm-6">
                <div class="form-group">
                  <label class="input-group-label">期望薪资：</label>
                  <input
                    type="text"
                    name="hope_salary"
                    class="form-control"
                    placeholder="请输入期望薪资"
                  />
                </div>
              </div>
              <div class="col-sm-6">
                <div class="form-group">
                  <label class="input-group-label">就业薪资：</label>
                  <input
                    type="text"
                    name="salary"
                    class="form-control"
                    placeholder="请输入就业薪资"
                  />
                </div>
              </div>
              <div class="col-sm-12">
                <div class="form-group">
                  <label class="input-group-label">籍贯：</label>
                  <div class="input pl-0">
                    <select class="form-select custom-select" name="province">
                      <option value="">--省份--</option>
                    </select>
                    <select class="form-select custom-select" name="city">
                      <option value="">--城市--</option>
                    </select>
                    <select class="form-select custom-select" name="area">
                      <option value="">--地区--</option>
                    </select>
                  </div>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-bs-dismiss="modal"
            >
              取消
            </button>
            <button type="button" class="btn btn-blue" id="submit">确认</button>
          </div>
        </div>
      </div>
    </div>
    <script src="./bootstrap/bootstrap.min.js"></script>
    <script src="./lib/axios.js"></script>
    <script src="./lib/form-serialize.js"></script>
    <script src="./js/common.js"></script>
    <script>
      /************ 渲染学生信息 ************/
      // 封装渲染函数(获取学生信息并渲染)
      async function renderList() {
        const { data: studentList } = await axios.get('/students')
        // console.log('学生信息--数组',studentList)
        // 渲染学生信息(定义一个空字符串、遍历数组、生成tr并拼接到一起，把拼接好的字符插入到指定位置)
        let str = ''
        studentList.forEach((item) => {
          str += `<tr>
                    <td>${item.name}</td>
                    <td>${item.age}</td>
                    <td>${item.gender === 0 ? '男生' : '女生'}</td>
                    <td>${item.group}</td>
                    <td>${item.hope_salary}</td>
                    <td>${item.salary}</td>
                    <td>${item.province} ${item.city} ${item.area}</td>
                    <td>
                      <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen" data-id="${item.id}"></i></a>
                      <a href="javascript:;" class="text-danger"><i class="bi bi-trash" data-id="${item.id}"></i></a>
                    </td>
                  </tr>`
        })
        document.querySelector('tbody').innerHTML = str
      }
      // 调用渲染函数
      renderList()

      /************ 删除学生 ************/
      // 给删除按钮注册单击事件 (委托)
      document
        .querySelector('tbody')
        .addEventListener('click', async function (e) {
          // 判断单击的是不是删除按钮? --判断类名
          // if (e.target.className === 'bi bi-trash') {
          //   console.log('单击了删除按钮')
          // }
          // contains()---判断是否包含某个类
          if (e.target.classList.contains('bi-trash')) {
            // console.log('单击了删除按钮')
            // 获取学生的id
            const id = e.target.dataset.id
            try {
              // 调接口(:id是路径参数---占位---放具体的参数值)
              await axios.delete(`/students/${id}`)
              // 重新渲染学生列表
              renderList()
            } catch (error) {
              alert('删除失败')
            }
          } else if (e.target.classList.contains('bi-pen')) {
            /************ 编辑学生 ************/
            // 4.1 单击“编辑”按钮，弹出编辑的模态框
            modal.show()
            document.querySelector('.modal-title').innerHTML = '编辑学员'
            // 获取学生的id
            const id = e.target.dataset.id
            // 给模态框盒子设置自定义属性data-id
            modalBox.dataset.id = id
            // 获取被编辑的学生的信息
            const {data:studentInfo} = await axios.get(`/students/${id}`) 
            // console.log('学生详情--对象',studentInfo)
            // 回显学生的信息到表单中
            // 获取所有的表单项（都有name属性）
            const ipts = [...modalBox.querySelectorAll('form [name]')]
            // 遍历表单项
            ipts.forEach(ipt => {
              // console.log('每一个表单项',ipt)
            // 获取表单项对应的 数据 (获取表单name属性的值)
              const k = ipt.name
              // console.log(k,studentInfo[k])
              // 给表单赋值---判断是不是性别的单选按钮
              if (k === 'gender') {
                // 设置被选中（性别的单选按钮有两个，每个按钮都有自己的value，如果单选按钮的value和学生的gender值一致，则让其选中）
                if (+ipt.value === studentInfo.gender) {
                  ipt.checked = true
                }
              } else {
                // 设置value
                ipt.value = studentInfo[k]
              }
            })
            /************ 市和区没有回显成功，但是省一变市就有数据了? why? 默认，下拉列表内容是空的 ************/
          // [1]获取城市数据并渲染（哪个省份下？）
          const { data: cArr } = await axios.get('/api/city', {
            params: {
              pname: pSelect.value,
            },
          })
          // 渲染城市数据到下拉列表中
          let str = ''
          cArr.forEach(item => {
            str += `<option value="${item}">${item}</option>`
          })
          // 所有选项的前面，放一个空选项
          cSelect.innerHTML = '<option value="">--城市--</option>' + str
          // [2]给城市下拉列表设置value即可
          cSelect.value = studentInfo.city
          // -------------------获取区的数据并渲染，给区下拉列表设置value即可--------------------------------------------
          const { data: aArr } = await axios.get('/api/area', {
            params: {
              pname: pSelect.value,
              cname: cSelect.value,
            },
          })
          // console.log('区县数据---数组', aArr)
          // 渲染区县数据到下拉列表中
          let str1 = ''
          aArr.forEach(item => {
            str1 += `<option value="${item}">${item}</option>`
          })
          // 所有选项的前面，放一个空选项
          aSelect.innerHTML = '<option value="">--区县--</option>' + str1
          aSelect.value = studentInfo.area
            // 单击“确认”，完成编辑功能
          }
        })

      /************ 添加学生 ************/
      // 单击"+"弹出模态框
      // 获取模态框盒子
      const modalBox = document.querySelector('#modal')
      // 创建模态框对象
      const modal = new bootstrap.Modal(modalBox)
      // 调用方法，控制显示和隐藏(show()显示/hide()隐藏)---一会马上就注释掉（测试代码）
      // modal.show()
      // setTimeout(function () {
      //   modal.hide()
      // }, 3000)
      document
        .querySelector('#openModal')
        .addEventListener('click', function () {
          // 显示模态框
          modal.show()
          // 修改标题
          document.querySelector('.modal-title').innerHTML = '添加学员'
          // 清空模态框盒子的表单(表单对象.reset())
          modalBox.querySelector('form').reset()

          /************ 提前规划(添加和编辑功能共用了同一个模态框盒子) ************/
          // 如何区分添加和编辑功能?方案:给模态框盒子添加自定属性
          /*
        如果是添加，给模态框盒子标签上添加自定义属性:<div class="modal fade" id="modal" data-id="add"></div>"
        如果是编辑，给模态框盒子标签上添加自定义属性:<div class="modal fade" id="modal" data-id="学生的id"></div>
        */
          // 给模态框盒子添加自定义属性
          modalBox.dataset.id = 'add'
        })

      // 省市区联动
      // 获取三个下拉列表元素对象
      const pSelect = document.querySelector('[name="province"]')
      const cSelect = document.querySelector('[name="city"]')
      const aSelect = document.querySelector('[name="area"]')
      // 获取所有的省份并渲染
      initProvince()
      async function initProvince() {
        // 获取省份数据
        const { data: pArr } = await axios.get('/api/province')
        // console.log('省份数据--数组',pArr)
        // 渲染省份数据到下拉列表中
        let str = ''
        pArr.forEach((item) => {
          str += `<option value="${item}">${item}</option>`
        })
        // 所有选项的前面，放一个空选项
        pSelect.innerHTML = '<option value="">--省份--</option>' + str
      }
      // 当省发生变化，市和区跟着变
      pSelect.addEventListener('change', async function () {
        // 区变--选项要清空
        aSelect.innerHTML = `<option value="">--区县--</option>`
        // 市变--选项要换成当前省份下的城市(发请求获取当前省份的城市数据 并 渲染)
        const { data: cArr } = await axios.get('/api/city', {
          params: {
            // pname:当前省份的值
            pname: pSelect.value,
          },
        })
        // console.log('城市数据--数组' ,cArr)
        // 梁城市数据到下拉列表中
        let str = ''
        cArr.forEach((item) => {
          str += `<option value="${item}">${item}</option>`
        })
        //所有选项的前面，放一个空选项
        cSelect.innerHTML = '<option value="">--城市--</option>' + str
      })
      // 当市发生变化，区跟着变
      cSelect.addEventListener('change', async function () {
        // 当前选择的市 cSelect.value
        // 获取当前选择的市 下面的区县数据并渲染
        const { data: aArr } = await axios.get('/api/area', {
          params: {
            pname: pSelect.value,
            cname: cSelect.value,
          },
        })
        // console.log('区县数据---数组',aArr)
        //染区县数据到下拉列表中
        let str = ''
        aArr.forEach((item) => {
          str += `<option value="${item}">${item}+</option>`
        })
        // 所有选项的前面，放一个空选项
        aSelect.innerHTML = '<option value="">--区县--</option>' + str
      })
      // 点击“确认”，完成添加功能
      // 给“确认”按钮注册单击事件
      document
        .querySelector('#submit')
        .addEventListener('click', async function () {
          // 收集表单数据
          const form = modalBox.querySelector('form')
          const data = serialize(form, { hash: true })

          data.age = +data.age
          data.gender = +data.gender
          data.group = +data.group
          data.hope_salary = +data.hope_salary
          data.salary = +data.salary
          // console.log(data)
          /************ 判断是添加还是编辑功能 ************/
          if (modalBox.dataset.id === 'add') {
            // 发送请求，调接口
          try {
            const res = await axios.post('/students', data)
            // 重新渲染即可
            renderList()
            // 关闭模态框
            modal.hide()
          } catch (error) {
            alert('添加学员失败！')
          }
          } else {
          // 编辑功能---调接口发送请求---关闭模态框---重新渲染列表
          const id = modalBox.dataset.id
          try {
            await axios.put(`/students/${id}`, data)
            modal.hide()
            renderList()
          } catch (error) {
            alert('编辑学员失败！')
          }
        }
        })
    </script>
  </body>
</html>
